package affd.converter;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeConnectionProtocol;
import org.artofsolving.jodconverter.office.OfficeManager;

/**
 * A OfficeConverter is a wrapper class for the JOD Converter. It simplifies the
 * creation of the JOD Converter's OfficeManager and provides a simple document
 * conversion function.
 * 
 * @author Joteitti joteitti@cc.hut.fi
 *
 */
public class OfficeConverter {
	
	private OfficeManager officeManager;
	private OfficeDocumentConverter officeConverter;
	private static Logger logger;
	
	static {
		// Create logger
		logger = Logger.getLogger("Converter");
	}
	
	/**
	 * Constructs a office converter.
	 * 
	 * @param home Path to the OpenOffice executable.
	 * @param ports OpenOffice ports to be used.
	 * @param timeout Timeout value for OpenOffice tasks. 
	 */
	public OfficeConverter(String home, int[] ports, long timeout) {
		// Start office manager
		try {
			officeManager = new DefaultOfficeManagerConfiguration()
				.setOfficeHome(home)
				.setConnectionProtocol(OfficeConnectionProtocol.SOCKET)
				.setPortNumbers(ports)
				.setTaskExecutionTimeout(timeout)
				.buildOfficeManager();
			officeManager.start();
			
			officeConverter = new OfficeDocumentConverter(officeManager);
		} catch(Exception e) {
			logger.log(Level.SEVERE, "Failed to construct office converter.", e);
		}
	}
	
	/**
	 * Converts files using the JOD Converter. The output format is defined
	 * from the output file's extension.
	 * 
	 * @param input Input filename.
	 * @param output Output filename.
	 * @return True if successfully converted otherwise false.
	 */
	public boolean convert(String input, String output) {
		try {
			// Create files
			File inputFile = new File(input);
			File outputFile = new File(output);
			
			logger.log(Level.INFO, "converting: \"" + input + "\" to \"" + output + "\"");
			
			long currentTime = System.currentTimeMillis();
			
			// Convert
			officeConverter.convert(inputFile, outputFile);
			
			// Calculate conversion time
			long deltaTime = System.currentTimeMillis() - currentTime;
			logger.log(Level.INFO, "converting \"" + input + "\" to \"" + output + "\" took " + deltaTime + " milliseconds.");
		} catch(Exception e) {
			logger.log(Level.WARNING, "Failed to convert \"" + input + "\".", e);
			return false;
		}
		
		return true;
	}
	
	/**
	 * Shutdowns the office converter.
	 */
	public void shutdown() {
		// Stop office manager
		officeManager.stop();
	}

}
